package com.zixuan.sina.config.security;

import com.zixuan.sina.config.security.filter.CheckTokenFilter;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configurable
@EnableWebSecurity//必须开启此注解 否则Security将不会生效
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private AnonymousAuthenticationHandler anonymousAuthenticationHandler;//未登录处理接口
    @Resource
    private LoginFaireHandler loginFaireHandler;//登录失败接口
    @Resource
    private LoginSuccessHandler loginSuccessHandler;//登录成功接口
    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;//认证权限
    @Resource
    private CommonUserDetailsService commonUserDetailsService;//userDetailService
    @Resource
    private CheckTokenFilter checkTokenFilter;//最先进入的就是它 其次是commonUserDetailsService
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){

        return new BCryptPasswordEncoder();
    }

    //配置认证信息
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(commonUserDetailsService).passwordEncoder(passwordEncoder());
    }

    //配置http请求拦截
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class);
           http.formLogin()
                .loginProcessingUrl("/api/user/login")
                .successHandler(loginSuccessHandler)//设置成功之后处理器
                .failureHandler(loginFaireHandler)//设置失败处理器
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/user/login","/api/user/add")
                   .permitAll()//放行登录接口
                .anyRequest().authenticated()
                .and()
                .exceptionHandling()
                .accessDeniedHandler(customerAccessDeniedHandler)//设置权限认证处理器
                .authenticationEntryPoint(anonymousAuthenticationHandler)//设置匿名登陆处理器
                .and().cors();
    }
}
